package fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.lanou.horo.myapplication.R;
import com.lanou.horo.myapplication.dbdao.HistoryEntity;
import com.lanou.horo.myapplication.dbdao.RecommendDbEntity;
import com.timqi.sectorprogressview.ColorfulRingProgressView;

import java.util.ArrayList;
import java.util.List;

import activity.MainActivity;
import dbdao.HistoryDBhelper;
import dbdao.RecommendDBHelper;
import de.greenrobot.event.EventBus;
import entity.MenuListEntity;
import application.BasisApplication;
import entity.PlayDetailsEntity;
import fragment.menufragments.MenuListFragment;
import service.MusicService;
import tools.PassingParametersInterface;
import utils.Common;
import utils.roundimage.RoundNetWorkImageView;
import tools.TimeUtil;
import utils.servicedown.MyDownReceiver;
import utils.texttools.StringUtil;
import utils.MessageEvent;
import utils.PlayMessage;

import volley.VolleySingleton;

/**
 * 播放界面
 * Created by dllo on 15/11/25.
 */
public class PlayFragment extends AbsBaseFragment implements View.OnClickListener, PassingParametersInterface {
    private RoundNetWorkImageView playFragmentImg, playBigImg;
    private TextView playTitle, playNum, playFragmentTitle, playFragmentSoundNum, playFragmentContent,
            playFragmentFsNum, playTargs, playTargsContent, playIntro, playIntroContent,
            playLyric, playLyricContent, playMenu, playdown, playshare, playHistory,playPraise;
    private String URL;
    private SeekBar musicProgress;
    private ImageView playBack, playPauseBtn, playPlayBtn, playLeft, playClock, playRight, focuse;
    private MusicService musicService;
    private ColorfulRingProgressView crpv;
    private long userId, albumid;
    private List<MenuListEntity.DataEntity> list;
    private int mScreenWidth;
    private MainActivity mainActivity;
    private DisplayMetrics metric;
    private int playingPosition, count =0;;
    private String BURL = "http://mobile.ximalaya.com/mobile/track/detail?device=android&trackId=";
    MyDownReceiver receiver;
    private HistoryDBhelper dBhelper;
    String playacv;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof MainActivity) {
            mainActivity = (MainActivity) activity;
            musicService = mainActivity.getMusicService();
        }
    }

    //开始的方法里面注册广播
    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Common.ACTION_DOWNLOAD_PROGRESS);
        filter.addAction(Common.ACTION_DOWNLOAD_SUCCESS);
        filter.addAction(Common.ACTION_DOWNLOAD_FAIL);
        getContext().registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);  //取消注册
    }

    public PlayFragment(long userId) {
        this.userId = userId;
        this.URL = BURL + userId;
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_play;
    }

    @Override
    protected void initView() {
        playHistory = findView(R.id.playHistory);
        playshare = findView(R.id.playshare);
        playClock = findView(R.id.playClock);
        crpv = findView(R.id.crpv);
        playNum = findView(R.id.playNum);
        playBack = findView(R.id.playBack);
        playMenu = findView(R.id.playMenu);
        playLeft = findView(R.id.playLeft);
        playRight = findView(R.id.playRight);
        playClock = findView(R.id.playClock);
        playTitle = findView(R.id.playTitle);
        playTargs = findView(R.id.playTargs);
        playIntro = findView(R.id.playIntro);
        playLyric = findView(R.id.playLyric);
        playBigImg = findView(R.id.playBigImg);
        playPlayBtn = findView(R.id.playPlayBtn);
        playPauseBtn = findView(R.id.playPauseBtn);
        musicProgress = findView(R.id.musicProgress);

        playdown = findView(R.id.playdown);
        receiver = new MyDownReceiver();
        focuse = findView(R.id.focuse);
        playPraise = findView(R.id.playPraise);
        playFragmentImg = findView(R.id.playFragmentImg);
        playTargsContent = findView(R.id.playTargsContent);
        playIntroContent = findView(R.id.playIntroContent);
        playLyricContent = findView(R.id.playLyricContent);
        playFragmentTitle = findView(R.id.playFragmentTitle);
        playFragmentFsNum = findView(R.id.playFragmentFsNum);
        playFragmentContent = findView(R.id.playFragmentContent);
        playFragmentSoundNum = findView(R.id.playFragmentSoundNum);

    }

    @Override
    protected void initData() {
        playPraise.setOnClickListener(this);
        playHistory.setOnClickListener(this);
        playshare.setOnClickListener(this);
        EventBus.getDefault().register(this); //注册EventBus
        dBhelper = HistoryDBhelper.getInstance();
        musicService.setMSeekBar(this.musicProgress);
        musicProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        playRight.setOnClickListener(this);
        playLeft.setOnClickListener(this);
        playMenu.setOnClickListener(this);
        playPlayBtn.setOnClickListener(this);
        playBack.setOnClickListener(this);
        playClock.setOnClickListener(this);
        playPauseBtn.setOnClickListener(this);
        metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        playdown.setOnClickListener(this);
        focuse.setOnClickListener(this);
        initNetwork();
    }

    String userImage, nickName, title;
    long aid, traid;


    /**
     * 网络请求
     */
    private void initNetwork() {
        VolleySingleton.getInstance().addRequest(URL,
                PlayDetailsEntity.class, new Response.Listener<PlayDetailsEntity>() {
                    @Override
                    public void onResponse(final PlayDetailsEntity response) {
                        if (response != null) {
                            playacv = response.getPlayPathAacv164();
                            setPlay(response);
                            setControlData(response);
                            saveBD(response);
                            initMuenNetwork();
                            dismissDialog();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dismissDialog();
                        toastError();
                    }
                });
        showDialog();
    }

    /**
     * 保存播放记录到数据库
     *
     * @param response
     */
    private void saveBD(PlayDetailsEntity response) {
        //点击播放  记录
        List<HistoryEntity> entities = new ArrayList<>();
        HistoryEntity entit = new HistoryEntity();
        entit.setAlbmid(response.getAlbumId());
        entit.setTrackId(response.getTrackId());
        entit.setTitle(response.getAlbumTitle());
        entit.setNickname(response.getCategoryName());
        entit.setSmallLogo(response.getCoverSmall());
        entit.setTimes(TimeUtil.getCurrentTime("yyyy-MM-dd HH:MM"));
        long trackId = response.getTrackId();
        entities.add(entit);
        HistoryDBhelper.getInstance().saveHost(entities);
    }

    /**
     * 判断播放
     *
     * @param response
     */
    private void setPlay(final PlayDetailsEntity response) {
        if (BasisApplication.getUserId() == userId) {
            if (!musicService.mediaPlayer.isPlaying()) {
                musicService.play();
                playPlayBtn.setVisibility(View.GONE);
                playPauseBtn.setVisibility(View.VISIBLE);
            }
        } else {
            BasisApplication.setUserId(userId);
            if (!musicService.mediaPlayer.isPlaying()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        musicService.playNow(response.getPlayPathAacv164());
                    }
                }).start();
            } else {
                musicService.stop();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        musicService.playNow(response.getPlayPathAacv164());
                    }
                }).start();
            }
        }
    }

    /**
     * 设置控件数据
     *
     * @param response
     */
    private void setControlData(PlayDetailsEntity response) {
        final String imageUrl = response.getCoverMiddle();
        final String user = response.getAlbumTitle();
        final String title = response.getTitle();
        new Thread(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(imageUrl);
                EventBus.getDefault().post(new MessageEvent(user, title, imageUrl));
            }
        }).start();
        playTitle.setText(title);
        playNum.setText(StringUtil.longToWan(response.getPlaytimes()));
        VolleySingleton.getInstance().getBitmap(imageUrl, playFragmentImg);
        VolleySingleton.getInstance().getBitmap(response.getCoverLarge(), playBigImg);
        if (response.getUserInfo() != null) {
            playFragmentSoundNum.setText("声音 " + StringUtil.longToWan(response.getUserInfo().getTracks()));
            playFragmentFsNum.setText("粉丝 " + StringUtil.longToWan(response.getUserInfo().getFollowers()));
            playFragmentContent.setText(response.getUserInfo().getPtitle());
        }
        playFragmentTitle.setText(user);
        if (!StringUtil.isEmpty(response.getTags())) {
            playTargs.setText("标签:  ");
            playTargsContent.setText(response.getTags());
        }
        if (!StringUtil.isEmpty(response.getIntro())) {
            playIntro.setText("简介:  ");
            playIntroContent.setText(response.getIntro());
        }
        if (!StringUtil.isEmpty(response.getLyric())) {
            playLyric.setText("歌词/文案:  ");
            playLyricContent.setText(response.getLyric());
        }
        albumid = response.getAlbumId();
    }

    /**
     * 接收通知栏传递的数据
     * 控制播放及按钮状态
     * 该方法在ui主线程执行
     */
    public void onEventMainThread(Integer i) {
        switch (i) {
            case 0:
                lastMusick();
                break;
            case 1:
                pauseMusick();
                break;
            case 2:
                goOnMusick();
                break;
            case 3:
                netxMusick();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.playHistory://播放历史
                goToMenu(new HistoryPageFragment());
                break;
            case R.id.playPraise://点赞之后
                break;
            case R.id.playshare://分享
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, "O(∩_∩)O哈哈~我正在听珠穆拉玛FM："
                        + title + "," + "点击:" + URL + "一起来收听吧(*^__^*) ");
                startActivity(intent);
                break;
            case R.id.playdown://点击下载的方法
                setPlaydown();
                break;
            case R.id.playBack:
                goBack();
                break;
            case R.id.playPauseBtn:
                pauseMusick();
                break;
            case R.id.playPlayBtn:
                goOnMusick();
                break;
            case R.id.playMenu:
                makeMenu();
                break;
            case R.id.playLeft:
                lastMusick();
                break;
            case R.id.playRight:
                netxMusick();
                break;
            case R.id.playClock://设置定时睡眠
                mainActivity.showSleepDialog();
                break;
            case R.id.focuse://关注的方法
                fouese();
                break;
        }
    }


    /**
     * 加入关注
     */
    private void fouese() {
        if (count==0){
            focuse.setImageResource(R.mipmap.player_followed);
            Toast.makeText(getContext(), "已关注", Toast.LENGTH_SHORT).show();
            count=1;
        }else if (count==1){
            focuse.setImageResource(R.mipmap.concern_btn_off_noraml);
            Toast.makeText(getContext(), "取消关注", Toast.LENGTH_SHORT).show();
            count=0;
        }



        //点击关注的时候存数据
        List<RecommendDbEntity> datas = new ArrayList<>();
        RecommendDbEntity entity = new RecommendDbEntity();
        entity.setNickname(nickName);
        entity.setSmallLogo(userImage);
        entity.setPlayUrl(playacv);
        entity.setUid(traid);
        entity.setAlbmid(aid);
        entity.setTitle(title);
        datas.add(entity);
        RecommendDBHelper.getInstance().saveRecommend(datas);
    }

    /**
     * //下载功能
     */
    private void setPlaydown() {
        Toast.makeText(getContext(), "加入下载列表", Toast.LENGTH_SHORT).show();
        String path = playacv;
        Log.d("PopularProgramPageFragm", path + "地址");
        String name = playFragmentTitle + ".mp3";
        if (DownloadService.getInstance() != null
                && DownloadService.getInstance().getFlag() != Common.Flag_Init) {
            Toast.makeText(getContext(), "已经在下载", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent it = new Intent(getContext(), DownloadService.class);
        it.putExtra("flag", "start");
        it.putExtra("url", path);
        it.putExtra("fileName", name);
        getContext().startService(it);
    }

    /**
     * 播放列表
     */
    private void makeMenu() {
        MenuListFragment menuListFragment = new MenuListFragment(list);
        menuListFragment.getParameters(this);
        goToMenu(menuListFragment);
    }

    /**
     * 继续播放
     */
    private void goOnMusick() {
        musicService.play();
        playPlayBtn.setVisibility(View.GONE);
        playPauseBtn.setVisibility(View.VISIBLE);
    }

    /**
     * 暂停
     */
    private void pauseMusick() {
        musicService.pause();
        playPauseBtn.setVisibility(View.GONE);
        playPlayBtn.setVisibility(View.VISIBLE);
    }

    /**
     * 下一首
     */
    private void netxMusick() {
        playingPosition = makePlayMenu();
        if (playingPosition < (list.size() - 1)) {
            userId = list.get(playingPosition + 1).getTrackId();
            this.URL = BURL + userId;
            initNetwork();
        } else {
            Toast.makeText(getContext(), "已经是最后一个了", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上一首
     */
    private void lastMusick() {
        playingPosition = makePlayMenu();
        if (playingPosition > 0) {
            userId = list.get(playingPosition - 1).getTrackId();
            this.URL = BURL + userId;
            initNetwork();
        } else {
            Toast.makeText(getContext(), "已经是第一个了", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void passingParameters(final Object o) {
        userId = (long) o;
        this.URL = BURL + userId;
        initNetwork();
    }

    //进度条
    private class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            this.progress = progress * musicService.mediaPlayer.getDuration()
                    / seekBar.getMax();
            crpv.setPercent(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // seekTo()的参数是相对与影片时间的数字，而不是与seekBar.getMax()相对的数字
            musicService.mediaPlayer.seekTo(progress);
        }
    }

    //stop 的时候关闭广播
    @Override
    public void onStop() {
        super.onStop();
        getContext().unregisterReceiver(receiver);
    }

    String menuURL;

    private void initMuenNetwork() {
        menuURL = "http://mobile.ximalaya.com/mobile/playlist/album?albumId=" + albumid + "&device=android&trackId=" + userId;
        VolleySingleton.getInstance().addRequest(menuURL,
                MenuListEntity.class, new Response.Listener<MenuListEntity>() {
                    @Override
                    public void onResponse(MenuListEntity response) {
                        if (response != null) {
                            list = response.getData();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        toastError();
                    }
                });
    }

    private int makePlayMenu() {
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                MenuListEntity.DataEntity l = list.get(i);
                if (l.getTrackId() == BasisApplication.getUserId()) {
                    return i;
                }
            }
        }
        return 0;
    }


}
